package conchmusic.conchmusicclient.activity;

import android.Manifest;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.adapter.SearchAdapter;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.pojo.SortMusic;
import conchmusic.conchmusicclient.util.InitPlayBar;
import conchmusic.conchmusicclient.util.PinyinComparator;
import conchmusic.conchmusicclient.util.SongGetScanMusic;
import conchmusic.conchmusicclient.view.PlayBar;

public class DownloadActivity extends AppCompatActivity {
    private ListView listView;
    private List<Song> downloadMusics;
    private SearchAdapter listViewAdapter;
    private ClientControl clientControl;
    private MyDBHelp myDBHelp;
    private MyReceiver myReceiver;
    private PinyinComparator pinyinComparator;
    private boolean isOnStart;
    private String[] list;
    private PlayBar playBar;
    private Intent intent;
    private Button btn_play;
    private int uid;
    private InitPlayBar initPlayBar;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        listView=(ListView)findViewById(R.id.download_listview_mymusic);
        btn_play=(Button)findViewById(R.id.playbar_play);
        downloadMusics=new ArrayList<>();
        pinyinComparator=new PinyinComparator();
        //数据库读localMusics
        myDBHelp=new MyDBHelp(this,"demon",null,1);
        clientControl=new ClientControl(myDBHelp);
        initAdapter();
        isOnStart=true;
        playBar=(PlayBar)findViewById(R.id.download_playbar);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                initPlayBar.itemInitPlaybar();
                intent=playMusic(position,list);
                Log.i("click list.size",list.length+"...");
                btn_play.setBackgroundResource(R.mipmap.ic_pause);
                startService(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflaterLocal=getMenuInflater();
        inflaterLocal.inflate(R.menu.download_mean_actionbar,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.start_online_search_activity:
                Log.i("clickserarch","onclick");
                Intent intent=new Intent(DownloadActivity.this,DownloadSearchActivity.class);
                startActivity(intent);
                return  true;
            case android.R.id.home:
                Intent upIntent = NavUtils.getParentActivityIntent(this);
                if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                    TaskStackBuilder.create(this)
                            .addNextIntentWithParentStack(upIntent)
                            .startActivities();
                } else {
                    upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    NavUtils.navigateUpTo(this, upIntent);
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        initPlayBar=new InitPlayBar(playBar,this);
        initPlayBar.initPlaybar();
        if(isOnStart){
            isOnStart=false;
        }else {
            initAdapter();
        }
        playBar.startMsgReceiver();
        myReceiver=new MyReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("conchmusic.conchmusicclient.downloadsuccess");
        DownloadActivity.this.registerReceiver(myReceiver,filter);
        Log.i("onResume","onResume");
    }

    public class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle=intent.getExtras();
            String info=bundle.getString("download");
            if(info.equals("success")){
                initAdapter();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(myReceiver);
        playBar.closeMsgReceiver();
    }
    public ArrayList<Song> getIndexSong(List<Song> songs){
        SongGetScanMusic songGetScanMusic=new SongGetScanMusic(songs);
        ArrayList<SortMusic> sortMusics=songGetScanMusic.getmSortList();
        ArrayList<Song> sortSongs=new ArrayList<>();
        Collections.sort(sortMusics,pinyinComparator);
        for(SortMusic sortMusic:sortMusics){
            sortSongs.add(sortMusic.getSong());
        }
        return sortSongs;
    }
    public void initAdapter(){
        downloadMusics=clientControl.findSongs(2);
        if(!downloadMusics.isEmpty()){
            downloadMusics=getIndexSong(downloadMusics);
            listViewAdapter = new SearchAdapter(this, downloadMusics);
            listView.setAdapter(listViewAdapter);
            list=new String[downloadMusics.size()];
            for(int i=0;i<downloadMusics.size();i++){
                list[i]=Integer.toString(downloadMusics.get(i).getLocalSongId());
                Log.i("list[]",i+"..."+list[i]);
            }
        }
    }
    public Intent playMusic(int position,String[] list){
        Intent intent=new Intent();
        intent.putExtra("action","playDirect");
        intent.putExtra("posit",position);
        intent.putExtra("songList",list);
        intent.setAction("music2");
        intent.setPackage(DownloadActivity.this.getPackageName());
        return intent;
    }
    public void notifyLocalMusic(){
    }
    public int getUid(){
        //注意修改
        this.uid=1;
        return this.uid;
    }
    @Override
    public void onBackPressed() {
        Log.i("onBack","onBack");
        super.onBackPressed();
        DownloadActivity.this.finish();
    }
}
